package com.myway.service.impl;

import com.myway.dto.common.JsonData;
import com.myway.dto.common.MD5Util;
import com.myway.dao.MyTabMemberInfoMapper;
import com.myway.dao.TabMemberInfoMapper;
import com.myway.dao.TabUserInfoMapper;
import com.myway.sms.msmUtil.InternationalSendSMS;
import com.myway.sms.msmUtil.SendEmail;
import com.myway.pojo.TabMemberInfo;
import com.myway.pojo.TabUserInfo;
import com.myway.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private TabUserInfoMapper tabUserInfoMapper;
    @Autowired
    private MyTabMemberInfoMapper myTabMemberInfoMapper;
    @Autowired
    private TabMemberInfoMapper tabMemberInfoMapper;

    /**
     * 发送短息验证码
     *
     * @param phoneNumber
     * @param request
     * @return
     */
    @Override
    public String getCode(String phoneNumber, HttpServletRequest request) {
        //去掉所有空格
        phoneNumber = phoneNumber.replaceAll("\\s*", "");
        InternationalSendSMS sd = new InternationalSendSMS();
        String code = (int) ((Math.random() * 9 + 1) * 100000) + "";
        System.out.println("短信验证码：\t" + code);
        request.getSession().setAttribute(phoneNumber, code);
        return sd.sendSms(phoneNumber, code);
    }

    /**
     * 手机短息验证码验证登陆
     *
     * @param phoneNumber
     * @param code
     * @param request
     * @return
     */
    @Override
    public JsonData phoneLogin(String phoneNumber, String code, HttpServletRequest request,
                               HttpServletResponse response) {
        //去掉所有空格
        phoneNumber = phoneNumber.replaceAll("\\s*", "");
        JsonData jsonData = new JsonData(true);
        JsonData jd = verificationPhone(phoneNumber, code, request);
        if (jd.isRet()) {//验证码正确
            //判断该手机用户是不是会员
            TabMemberInfo tbm = new TabMemberInfo();
            tbm.setMembPhoneNum(phoneNumber);
            List<TabMemberInfo> tabMemberInfo = myTabMemberInfoMapper.selectMemb(tbm);
            //该手机号为会员用户
            if (tabMemberInfo.size() > 0) {
                jsonData.setMsg("600");
                jsonData.setData(tabMemberInfo);
                return jsonData;
            } else {
                //非会员用户
                TabUserInfo tuf = new TabUserInfo();
                tuf.setUserPhoneNum(phoneNumber);
                tuf.setUserLoginTime(new Date());
                TabUserInfo tabUserInfo = tabUserInfoMapper.selectByPrimaryKey(phoneNumber);
                //该手机用户不存在插入该用户，存在则修改该用户
                if (tabUserInfo == null) {
                    tabUserInfoMapper.insert(tuf);
                } else {
                    tabUserInfoMapper.updateByPrimaryKeySelective(tuf);
                }
                jsonData.setMsg("200");
                return jsonData;
            }
        } else {
            //手机验证码不正确
            jd.setMsg("404");
            return jsonData;
        }
    }

    /**
     * 查找会员是否存在
     *
     * @param keyword
     * @return
     */
    @Override
    public JsonData membLogin(String keyword) {
        TabMemberInfo tmi = regular(keyword);//判断关键字类型
        JsonData jsonData = null;
        if (tmi != null) {
            List<TabMemberInfo> tabMemberInfo = myTabMemberInfoMapper.selectMemb(tmi);
            if (tabMemberInfo != null) {
                jsonData = new JsonData(true);
                jsonData.setData(tabMemberInfo);
                jsonData.setMsg("用户存在");
                return jsonData;
            } else {
                jsonData = new JsonData(false);
                jsonData.setMsg("用户不存在");
                return jsonData;
            }
        } else {//输入的关键字不是用户登录名
            jsonData = new JsonData(false);
            jsonData.setMsg("账号格式不正确");
            return jsonData;
        }
    }

    /**
     * 会员密码修改
     *
     * @param request
     * @param oldPwd
     * @param newPwd
     * @param verificationCode
     * @return
     */
    @Override
    public JsonData changePwd(HttpServletRequest request, String oldPwd,
                              String newPwd, String verificationCode) {
        JsonData jsonData = null;
        HttpSession session = request.getSession();
        TabMemberInfo member = (TabMemberInfo) session.getAttribute("member");
        //判断会员是否登陆
        if (member == null) {
            jsonData = new JsonData(false);
            jsonData.setMsg("请先登录！");
            return jsonData;
        }
        TabMemberInfo tabMemberInfo = tabMemberInfoMapper.selectByPrimaryKey(member.getMembId());
        //判断会员是否存在
        if (tabMemberInfo == null) {
            jsonData = new JsonData(false);
            jsonData.setMsg("会员不存在！");
            return jsonData;
        }
        //判断输入旧密码是否正确
        if (!tabMemberInfo.getMembPwd().equals(MD5Util.string2MD5(oldPwd))) {
            jsonData = new JsonData(false);
            jsonData.setMsg("pwdError");
            return jsonData;
        }
        //判断验证码是否正确
        if (session.getAttribute("IMG_VALIDATE_KEY").toString().equalsIgnoreCase(verificationCode)) {
            tabMemberInfo.setMembPwd(MD5Util.string2MD5(newPwd));
            tabMemberInfoMapper.updateByPrimaryKeySelective(tabMemberInfo);
            jsonData = new JsonData(true);
            jsonData.setMsg("密码修改成功");
            return jsonData;
        } else {
            jsonData = new JsonData(false);
            jsonData.setMsg("vCodeError");
            return jsonData;
        }
    }

    /**
     * 忘记密码，找回密码，支持手机号验证码和邮箱两种方式
     *
     * @param memberInfo
     * @return
     */
    @Override
    public JsonData forgetPwd(TabMemberInfo memberInfo) {
        String phoneNum = memberInfo.getMembPhoneNum();
        String email = memberInfo.getMembEmail();
        if (phoneNum != null && !"".equals(phoneNum)) {
            //去掉所有空格
            phoneNum = phoneNum.replaceAll("\\s*", "");
            memberInfo.setMembPhoneNum(phoneNum);
            int i = tabMemberInfoMapper.updateByPrimaryKeySelective(memberInfo);
            if (i == 0) {
                return new JsonData(false);
            } else {
                return new JsonData(true);
            }
        } else if (email != null && !"".equals(email)) {
            int i = tabMemberInfoMapper.updateByPrimaryKeySelective(memberInfo);
            if (i == 0) {
                return new JsonData(false);
            } else {
                return new JsonData(true);
            }
        } else {
            return new JsonData(false);
        }
    }

    @Override
    public String getEmailCode(String email, HttpServletRequest request) {
        //去掉所有空格
        SendEmail sd = new SendEmail();
        String code = (int) ((Math.random() * 9 + 1) * 100000) + "";
        request.getSession().setAttribute(email, code);
        sd.sendMail(email, code);
        return "OK";
    }

    /**
     * 验证邮箱账号是否存在，存在则修改密码，不存在返回错误信息
     *
     * @param email
     * @return
     */
    @Override
    public JsonData EmailVerific(String email, String newPwd) {
        JsonData jsonData = new JsonData(true);
        //判断该邮箱用户是不是会员
        TabMemberInfo tbm = new TabMemberInfo();
        tbm.setMembEmail(email);
        tbm.setMembPwd(MD5Util.string2MD5(newPwd));
        List<TabMemberInfo> tabMemberInfo = myTabMemberInfoMapper.selectMemb(tbm);
        //该邮箱为会员用户
        if (tabMemberInfo.size() > 0) {
            tbm.setMembId(tabMemberInfo.get(0).getMembId());
            //调用forget修改会员密码
            JsonData jsond = forgetPwd(tbm);
            if (jsond.isRet()) {
                jsonData.setMsg("OK");
                return jsonData;
            } else {
                jsonData.setMsg("error");
                return jsonData;
            }
        } else {
            //非会员用户
            jsonData.setMsg("邮箱账号不存在！");
            return jsonData;
        }
    }

    //判断账号类型<只在会员登陆时用到>
    public TabMemberInfo regular(String str) {
        //去掉所有空格
        str = str.replaceAll("\\s*", "");
        TabMemberInfo tabMemberInfo = new TabMemberInfo();
        String checkEmail = "^([a-z0-9A-Z]+[-|_|\\.]?)+[a-z0-9A-Z]" +
                "@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
        String checkMobileNumber = "^(((13[0-9])|(15([0-3]|[5-9]))|(18[0,5-9]))" +
                "\\d{8})|(0\\d{2}-\\d{8})|(0\\d{3}-\\d{7})$";
        String checkCreNum = "^[1-9]\\d{5}(18|19|([23]\\d))\\d{2}((0[1-9])" +
                "|(10|11|12))(([0-2][1-9])|10|20|30|31)\\d{3}[0-9Xx]$";
        String checkPassport = "^[a-zA-Z0-9]{5,17}$";
        String checkInternationalNum = "\\+[1-9]\\d*";
        String reg = "\\+(9[976]\\d|8[987530]\\d|6[987]\\d|5[90]\\d|42\\d|3[875]\\d|\n" +
                "2[98654321]\\d|9[8543210]|8[6421]|6[6543210]|5[87654321]|\n" +
                "4[987654310]|3[9643210]|2[70]|7|1)\\d{1,14}$";
//        String REGEX_ID_PASSPORT = " /^1[45][0-9]{7}|([P|p|S|s]\\d{7})|([S|s|G|g]\\d{8})|([Gg|Tt|Ss|Ll|Qq|Dd|Aa|Ff]\\d{8})|([H|h|M|m]\\d{8,10})$/";

        //有问题待完善
        if (check(checkEmail, str)) {
            tabMemberInfo.setMembEmail(str);
            return tabMemberInfo;
        } else if (check(checkCreNum, str)) {
            tabMemberInfo.setMembCertNum(str);
            return tabMemberInfo;
        } else if (check(checkPassport, str)) {
            tabMemberInfo.setMembCertNum(str);
            return tabMemberInfo;
        } else if (check(checkMobileNumber, str)) {
            tabMemberInfo.setMembPhoneNum(str);
            return tabMemberInfo;
        } else if (check(checkInternationalNum, str)) {
            tabMemberInfo.setMembPhoneNum(str);
            return tabMemberInfo;
        } else {
            return null;
        }
    }

    //    判断string是否符合某种正则
    public static boolean check(String check, String str) {
        boolean flag = false;
        try {
            Pattern regex = Pattern.compile(check);
            Matcher matcher = regex.matcher(str);
            flag = matcher.matches();
        } catch (Exception e) {
            flag = false;
        }
        return flag;
    }

    //邮箱验证码验证
    @Override
    public JsonData verificationEmail(String email, String code, HttpServletRequest request) {
        HttpSession session = request.getSession();
        Object ob = session.getAttribute(email);
        if (ob != null) {
            String str = ob.toString();
            if (str != null && !"".equals(str) && code != null && !"".equals(str) && str.equals(code)) {
                session.removeAttribute(email);
                return new JsonData(true);
            } else {
                session.removeAttribute(email);
                return JsonData.fail("验证码不正确");
            }
        } else {
            return JsonData.fail("验证码无效");
        }


    }

    //手机验证码验证
    @Override
    public JsonData verificationPhone(String phoneNum, String code, HttpServletRequest request) {
        HttpSession session = request.getSession();
        Object ob = session.getAttribute(phoneNum);
        if (ob != null) {
            String str = ob.toString();
            if (str != null && !"".equals(str) && str.equals(code)) {
                session.removeAttribute(phoneNum);
                return new JsonData(true);
            } else {
                session.removeAttribute(phoneNum);
                return JsonData.fail("验证码不正确");
            }
        } else {
            return JsonData.fail("验证码无效");
        }

    }

}
